import socket
import threading

def main():
    # 创建TCP服务器并绑定到8080端口
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('0.0.0.0', 8080))
    server_socket.listen(5)
    
    # 存储所有连接的客户端
    clients = []
    
    # 广播消息给所有客户端
    def broadcast(message, sender_socket=None):
        for client in clients:
            # 不向发送者本人广播
            if client != sender_socket:
                try:
                    client.send(message)
                except:
                    # 如果发送失败，移除该客户端
                    clients.remove(client)
    
    # 处理客户端消息
    def handle_client(client_socket):
        while True:
            try:
                # 接收客户端消息
                data = client_socket.recv(1024)
                if not data:
                    # 如果没有数据，说明客户端断开连接
                    clients.remove(client_socket)
                    client_socket.close()
                    break
                
                # 打印接收到的消息
                message = data.decode('utf-8').strip()
                print(f"收到消息: {message}")
                
                # 广播消息给所有其他客户端
                broadcast(data, client_socket)
                
            except Exception as e:
                print(f"客户端连接断开: {e}")
                clients.remove(client_socket)
                client_socket.close()
                break
    
    # 接收控制台输入并广播给所有客户端
    def console_input():
        while True:
            try:
                message = input()
                if message.lower() == 'quit':
                    # 退出服务器
                    server_socket.close()
                    exit()
                
                # 广播服务器消息
                broadcast(f"服务器: {message}".encode('utf-8'))
                
            except Exception as e:
                print(f"输入错误: {e}")
                break
    
    # 启动控制台输入线程
    input_thread = threading.Thread(target=console_input)
    input_thread.daemon = True
    input_thread.start()
    
    print("服务器已启动，监听端口 8080...")
    
    # 主循环：监听并接受客户端连接
    while True:
        try:
            client_socket, client_address = server_socket.accept()
            print(f"客户端连接: {client_address}")
            
            # 添加客户端到列表
            clients.append(client_socket)
            
            # 为每个客户端创建新线程处理消息接收
            client_thread = threading.Thread(target=handle_client, args=(client_socket,))
            client_thread.daemon = True
            client_thread.start()
            
        except Exception as e:
            print(f"服务器错误: {e}")
            break

if __name__ == "__main__":
    main()